
package com.borqs.music.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Base64;

public class MD5Utils {

    public static String getMD5(byte[] bytes) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(bytes);
            return toHexString(algorithm.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5Base64(byte[] bytes) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.update(bytes);
            return Base64.encodeToString(algorithm.digest(), Base64.NO_WRAP);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getMD5(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            return null;
        }

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int len = -1;
            while ((len = fis.read(buffer)) > -1) {
                messagedigest.update(buffer, 0, len);
            }
            fis.close();

            return toHexString(messagedigest.digest());
        } catch (NoSuchAlgorithmException nae) {
            nae.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return null;
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hexStr = Integer.toHexString(0xFF & b);
            if (hexStr.length() == 1) {
                hexString.append("0");
            }

            hexString.append(hexStr);
        }

        return hexString.toString();
    }
}
